package com.example.administrator.szb.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.HDXQAdapter;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.bean.AskHD;
import com.example.administrator.szb.bean.GZBean;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.example.administrator.szb.R.id.wtxq_edit_srhd;
import static com.example.administrator.szb.R.id.wtxq_text_fs;

/**
 * Created by D N on 2017/9/23.
 */

public class HDXQActivity extends MVPBaseActivity implements HDXQAdapter.OnItemClickListener{
    //问题id
    private  int refer_id;
    //回复另外人的id,默认是本问题的人的id
    private int other_id;
    private String image;
    private int tmp_uid;
    private LinearLayout wtxq_text_djsc;
    private ListView listView;
    private TextView send_btn;
    private EditText editText;
    private CircleImageView head_img;
    private TextView name;
    private TextView del_or_gz;
    private TextView content;
    private TextView pinglunCount,bar_title;
    private View bantouming;
    private InputMethodManager imm;
    private HDXQAdapter adapter;
    private AskHD askHD;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hdxq_activity);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return getWindow().superDispatchTouchEvent(ev);
    }
    @Override
    protected void initView() {
        initKey();
        listView = findViewById(R.id.listView);

        bantouming = findViewById(R.id.bantouming);
        bantouming.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKey(v);
                return true;
            }
        });
        wtxq_text_djsc  = findViewById(R.id.wtxq_text_djsc);
        wtxq_text_djsc.setVisibility(View.GONE);
        head_img = (CircleImageView) findViewById(R.id.head_img);
        name = (TextView) findViewById(R.id.name);
        del_or_gz = (TextView) findViewById(R.id.del_or_gz);
        content = (TextView) findViewById(R.id.content);
        pinglunCount = (TextView) findViewById(R.id.pinglunCount);
        editText = (EditText) findViewById(wtxq_edit_srhd);
        send_btn = (TextView) findViewById(wtxq_text_fs);
        bar_title = (TextView) findViewById(R.id.bar_title);
        bar_title.setText("回答详情");
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);//实例化软键盘
    }

    @Override
    protected void initEvent() {
        head_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, GWCententActivity.class);
                intent.putExtra("refer_id", other_id);
                startActivity(intent);
            }
        });
        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                    DialogUtil.showSimpleDialog(context, "请输入回答内容！");
                    return;
                }
                //发送数据
                sendMessages();
            }

        });
        del_or_gz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin()){
                    return;
                }
                if (SPUtils.getUserId()==other_id){
                    //自己
                    new AlertDialog.Builder(context)
                            .setTitle("提示")
                            .setMessage("确认删除？")
                            .setNegativeButton("取消",null)
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requsetDel();
                                }
                            }).show();

                }else {
                    doRequestGz();
                }
            }
        });

        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QTLog.e("bbbbbbbbb");
                editTextOut(true);
            }
        });
        //wtxq_edit_srhd.focus(false);
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                editTextOut(true);
            }
        });
    }

    @Override
    protected void initData() {
        refer_id = getIntent().getIntExtra("refer_id", 0);
        other_id = getIntent().getIntExtra("quiz_id",-1);
        image = getIntent().getStringExtra("image");
        tmp_uid = other_id;

        requestData();
    }
    @Override
    public void editTextOut(boolean isshow) {
        if (isshow){
            QTLog.e("软键盘弹起");
            bantouming.setVisibility(View.VISIBLE);
            editText.setLines(5);
            //wtxq_text_djsc.setVisibility(View.GONE);
            send_btn.setVisibility(View.VISIBLE);
        }else {
            QTLog.e("软键盘关闭");
            bantouming.setVisibility(View.GONE);
            editText.setLines(1);
            send_btn.setVisibility(View.GONE);
            //wtxq_text_djsc.setVisibility(View.VISIBLE);
        }

    }
    private void requestData(){
        Map<String,Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("refer_id", refer_id + "");
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        HttpUtils.post(activity,URLAddress.URLBASE + URLAddress.URL_HDXQ, map, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                 askHD = JSON.parseObject(str,new TypeReference<AskHD>(){});
                Glide.with(context).load(image).error(R.mipmap.default_header_s).into(head_img);
                name.setText(askHD.getName());
                content.setText(askHD.getContent());
                if (SPUtils.getUserId()==other_id){
                    //自己
                    del_or_gz.setText("删除回答");
                }else {
                    del_or_gz.setText("关注");
                    if (askHD.getIs_attention()==1){
                        del_or_gz.setText("已关注");
                    }
                }





                pinglunCount.setText(""+askHD.getDiscuss().size()+"评论");
                initPinglun();
            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });
    }
    private void sendMessages(){
        if (!isLogin()){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("refer_id", refer_id + "");
        map.put("content", editText.getText().toString().trim());
        map.put("by_reply_id", tmp_uid + "");
        HttpUtils.post(activity,URLAddress.URLBASE + URLAddress.URL_HDHF, map, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                WTContentActivity.canRefresh = true;
                reset();
                DialogUtil.showToast(context,"发送成功");
            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });

    }




    /**
     * 重置状态
     */
    private void reset() {
        tmp_uid = other_id;

        editText.setText("");
        editText.setHint("输入我的回答");
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }

        }
        requestData();
    }
    private List<AskHD.DiscussBean> discussBeanList;
    private void initPinglun(){
        if (discussBeanList==null){
            discussBeanList = new ArrayList<>();
        }
        discussBeanList.clear();
        discussBeanList.addAll(askHD.getDiscuss());

        if (discussBeanList.size()>0){
            listView.setBackgroundColor(getResources().getColor(R.color.white));
        }else {
            listView.setBackgroundColor(Color.parseColor("#f3f3f3"));
        }


        if (adapter==null){
            adapter = new HDXQAdapter(context,discussBeanList,other_id);
            adapter.setOnItemClickListener(this);
            listView.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }
    }
    private boolean isLogin(){
        if (SPUtils.getUserId()==0){
            Intent intent = new Intent(context,LoginNewActivity_two.class);
            startActivity(intent);
         return false;
        }
        return true;
    }



    @Override
    public void onItemClick(int id, String name) {
        if (!isLogin()){
            return;
        }
        tmp_uid = id;
        editText.setText("");
        editText.setHint("回复"+name);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        imm.showSoftInput(editText, 0);

    }

    /**
     * 执行关注
     */
    private void doRequestGz() {

        if (!(SPUtils.isLogin())){
            startActivity(new Intent(context,LoginNewActivity_two.class));
            return;
        }
        if (other_id==SPUtils.getUserId()){
            DialogUtil.showToast(context,"不能收藏自己");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        int id = SampleApplicationLike.getUserloginInstance().getId();
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("quiz_id", other_id + "");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, GZBean.class, URLAddress.URLBASE + URLAddress.URL_GZ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                GZBean gzBean = (GZBean) response;
                if (gzBean.getResult() == 1) {
                    if (gzBean.getData().getCode()==0){
                        del_or_gz.setText("关注");
                    }else {
                        del_or_gz.setText("已关注");
                    }
                    //DialogUtil.showSimpleDialog(HDXQActivity.this, gzBean.getData().getMsg());
                    //requestData();
                    Toasts.show(HDXQActivity.this, ""+gzBean.getData().getMsg(), Toast.LENGTH_SHORT);
                } else {
                    // DialogUtil.showSimpleDialog(HDXQActivity.this, gzBean.getErr_msg());
                    //del_or_gz.setText("关注");

                    Toasts.show(HDXQActivity.this, ""+gzBean.getData().getMsg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
                //DialogUtil.showSimpleDialog(HDXQActivity.this, "服务器异常，请重新尝试");
                Toasts.show(HDXQActivity.this, "发生异常。。。", Toast.LENGTH_SHORT);
            }
        });
    }

    private void requsetDel() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("refer_id", refer_id+"");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_DEL_HD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rZBean = (RzBean) response;
                if (rZBean.getResult() == 1){
                    WTContentActivity.canRefresh = true;
                    Toasts.show(HDXQActivity.this, "删除成功", Toast.LENGTH_SHORT);
                    finish();
                }else {
                    Toasts.show(HDXQActivity.this, ""+rZBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toasts.show(HDXQActivity.this, ""+error.toString(), Toast.LENGTH_SHORT);
            }
        });
    }



}
